<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :destroy-on-close="true"
    :close-on-click-modal="false"
    width="650px">
    <el-form
      :model="form"
      :rules="rule"
      ref="form"
      style="width: 560px"
      label-width="100px"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio :label="0">显示</el-radio>
          <el-radio :label="1">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" style="display: flex;justify-content: center;">
      <el-button type="primary"
                 @click="cancel">取消
      </el-button>
      <el-button type="primary"
                 @click="submit">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { edit, create } from '../api'
export default {
  name: 'view-dialog',
  data () {
    return {
      dialogVisible: false,
      id: undefined,
      form: {
        name: '',
        status: 0
      },
      rule: {
        name: [
          { required: true, message: '请输入拒绝理由' }
        ]
      }
    }
  },
  computed: {
    title () {
      return this.id === undefined ? '新增分类' : '编辑分类'
    }
  },
  methods: {
    handleClose (done) {
      done()
    },
    open (row = false) {
      if (row === false) {
        this.form = {
          name: '',
          status: 0
        }
        this.id = undefined
      } else {
        const { id, name, status } = row
        Object.assign(this.form, { name, status })
        this.id = id
      }
      this.dialogVisible = true
      return new Promise((resolve) => {
        this._resolve = resolve
      })
    },
    cancel () {
      this.close()
    },
    close () {
      this.dialogVisible = false
      this._resolve({ refresh: true })
    },
    async submit () {
      await this.$refs.form.validate()
      if (this.id === undefined) {
        await create(this.form)
      } else {
        await edit(this.id, this.form)
      }
      this.$message.success('更新成功')
      this.close()
    }
  }
}
</script>

<style scoped>

</style>
